package dk.itu.spct;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Observable;
import java.util.Observer;

import javax.imageio.ImageIO;

public class ImageServer extends Observable implements Runnable {
	
	Socket socket;
	InputStream is;
	int serverPort = 12345;
	ServerSocket serverSocket;
	
	public ImageServer(Observer obs) {
		this.addObserver(obs);
		try {
			serverSocket = new ServerSocket(serverPort);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	@Override
	public void run() {
		while(true) {
			
			BufferedImage img = null;
			
			try {
		    socket = serverSocket.accept();
		    InputStream is = socket.getInputStream();
		    img = ImageIO.read(is);
		    socket.close();
		    
			} catch (UnknownHostException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			/*
			
			try {
			    socket = serverSocket.accept();
				is = socket.getInputStream();
				DataInputStream dis = new DataInputStream(is);
				int len = dis.readInt();
				byte[] byteArray =  new byte[len];
				dis.readFully(byteArray);
				img = ImageIO.read(new ByteArrayInputStream(byteArray));
				socket.close();
			} catch (UnknownHostException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}*/
			
			
			if(img != null) {
				this.setChanged();
				this.notifyObservers(img);
			}
		}
	}
}
